package com.yksj.healthtalk.ui.salon;

import java.util.ArrayList;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import org.handmark.pulltorefresh.library.PullToRefreshListView;

import sfs2x.client.core.SFSEvent;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.yksj.healthtalk.adapter.SearchAdapter;
import com.yksj.healthtalk.adapter.SearchAdapter.onClickSalonAttentionListener;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.db.ChatUserHelper;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.GroupInfoEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.CoreService;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.chatting.ChatActivity;
import com.yksj.healthtalk.ui.salon.SalonSelectPaymentOptionActivity.OnBuyTicketHandlerListener;
import com.yksj.healthtalk.utils.SalonHttpUtil;
import com.yksj.healthtalk.utils.ToastUtil;
/**
 * 医生话题
 * @author jack_tang
 *
 */
public class SalonAboutOthersActivity extends BaseFragmentActivity implements
		OnClickListener, OnItemClickListener, OnBuyTicketHandlerListener, onClickSalonAttentionListener {

	private PullToRefreshListView mPullToRefreshListView;
	private ListView mListView;
	public int pagesize = 1;
	private int pagenum = 20;
	private ArrayList<GroupInfoEntity> entities;
	private SearchAdapter<GroupInfoEntity> mSalonAdapter;
	private GroupInfoEntity cacheGroupInfoEntity;
	private CustomerInfoEntity entity;
	private AppData mAppData;
	private String type = "1"; // 0-只有医生话题 1-普通

	BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_COLLECT_GROUP_NOT)) {
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(SalonAboutOthersActivity.this, R.string.groupNewFail);
				} else {
					SalonHttpUtil.requestUnfollowToSalonResult(SalonAboutOthersActivity.this,cacheGroupInfoEntity, mAppData, chatUserHelper);
					mSalonAdapter.notifyDataSetChanged();
				}
			} else if (action.equals(MessagePushService.ACTION_COLLECT_GROUP)) {
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(SalonAboutOthersActivity.this, R.string.groupNewFail);
				} else {
					SalonHttpUtil.requestAttentionToSalonResult(SalonAboutOthersActivity.this,cacheGroupInfoEntity, mAppData, chatUserHelper);
					mSalonAdapter.notifyDataSetChanged();
				}
			} else if (action.equals(SFSEvent.CONNECTION_LOST)) {
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
			} else if (action.equals(CoreService.ACTION_MESSAGE)) {
				if (intent.hasExtra("senderId")) {
//					String id = intent.getStringExtra("senderId");
//					if (mAppData.getInterestGroupIdList().contains(id)) {
						mSalonAdapter.notifyDataSetChanged();
//					}
				}

			}
		}

	};
	private ChatUserHelper chatUserHelper;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.salon_others);
		chatUserHelper = ChatUserHelper.getInstance();
		initWidget();
		initData();
	}

	@Override
	protected void onStart() {
		if (mPullToRefreshListView != null) {
			if (mPullToRefreshListView.isRefreshing()) {
				mPullToRefreshListView.onRefreshComplete();
			} else {
				mPullToRefreshListView.setRefreshing();
			}
		}
		pagesize = 1;
		getSalons(pagesize);
		IntentFilter filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_COLLECT_GROUP_NOT);
		filter.addAction(MessagePushService.ACTION_MESSAGE);
		filter.addAction(MessagePushService.ACTION_COLLECT_GROUP);
		filter.addAction(SFSEvent.CONNECTION_LOST);
		registerReceiver(mReceiver,filter);
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
		unregisterReceiver(mReceiver);
	}

	private void initData() {
		Intent intent = getIntent();
		// 判断是否是其他人的话题
		if (intent.hasExtra("mInfoEntity")) {
			entity = (CustomerInfoEntity) intent.getExtras().get("mInfoEntity");
		} else {
			entity = SmartFoxClient.getLoginUserInfo();
		}
		
		// // 0-只有医生话题 1-普通
		if (intent.hasExtra("type")) {
			type = intent.getStringExtra("type");
		}
		// type == 0是医师话题 entity是不是自己的话题 == 家园专业话题
		if (type.equals("0")) {
			if (entity.getId().equals(SmartFoxClient.getLoginUserId())) {
				titleRightBtn2.setVisibility(View.VISIBLE);
			}
			titleTextV.setText("话题管理");
		} else {
			titleTextV.setText("TA的话题");
		}
		
		if(!TextUtils.isEmpty(getIntent().getStringExtra("title"))){
			titleTextV.setText(getIntent().getStringExtra("title"));
		}

		entities = new ArrayList<GroupInfoEntity>();
		mAppData = HTalkApplication.getAppData();
		mSalonAdapter = new SearchAdapter<GroupInfoEntity>(this, entities);
		mSalonAdapter.setonClickSalonAttentionListener(this);
		mListView.setAdapter(mSalonAdapter);
		if (SmartFoxClient.getLoginUserId() == null) {
			return;
		}
		
		mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener2<ListView>() {

					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						pagesize = 1;
						getSalons(pagesize);
					}

					@Override
					public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
						getSalons(++pagesize);
					}

				});
	}

	/**
	 * 获取创建的话题
	 * 
	 * @param pagenum
	 */
	private void getSalons(final int pagesize) {
		HttpRestClient.doHttpOthersPersonSalon(entity.getId(), pagesize,
				pagenum, type,SmartFoxClient.getLoginUserId(), new AsyncHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, String content) {
						if (pagesize == 1) {
							entities.clear();
						}
						ArrayList<GroupInfoEntity> e = SalonHttpUtil.jsonAnalysisSalonEntity(content);
						entities.addAll(e);
						mSalonAdapter.notifyDataSetChanged();
						super.onSuccess(statusCode, content);
					}

					@Override
					public void onFinish() {
						mPullToRefreshListView.onRefreshComplete();
						super.onFinish();
					}
				});
	}

	private void initWidget() {
		initTitle();
		titleRightBtn2.setText("创建");
		mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.hall);
		mListView = mPullToRefreshListView.getRefreshableView();
		titleLeftBtn.setOnClickListener(this);
		titleRightBtn2.setOnClickListener(this);
		mListView.setOnItemClickListener(this);
		mListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.list_line_layout, null));
		
	}

	@Override
	public void onClick(View v) {
		if (v.getTag() != null && v.getTag() instanceof Integer) {
			int position = (Integer) v.getTag();
			String id = entities.get(position).getCreateCustomerID();
			Intent intent = new Intent();
			if (id.equals(SmartFoxClient.getLoginUserId())) {
				intent.setClass(getApplicationContext(), SalonReadSelf.class);
			} else {
				intent.setClass(getApplicationContext(),SalonInformationActivity.class);
			}
			Bundle bundle = new Bundle();
			intent.putExtra("id", entities.get(position).getId());
			intent.putExtras(bundle);
			startActivity(intent);
		} else {
			switch (v.getId()) {
			case R.id.title_back:
				finish();
				break;
			case R.id.title_right2:
				Intent intent = new Intent(this, SalonNewActivity.class);
				intent.putExtra("isDoctorSalon", true);
				startActivity(intent);
				break;
			default:
				break;
			}
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (position >= 1 && position <= entities.size()) {
			SalonHttpUtil.onItemClick(getApplicationContext(), this,
					getSupportFragmentManager(), entities.get(position - 1),
					false);
		}

	}

	@Override
	public void onTicketHandler(String state, GroupInfoEntity entity) {
		if ("0".equals(state)) {
//			ToastUtil.showShort(getApplicationContext(), "多美币不足");
		} else if ("-1".equals(state)) {
			ToastUtil.showShort(getApplicationContext(), "服务器出错");
		} else {
			Intent intent1 = new Intent();
			intent1.putExtra(ChatActivity.KEY_PARAME, entity);
			intent1.setClass(getApplicationContext(), ChatActivity.class);
			startActivity(intent1);
		}
	}

	/**
	 * 关注回调
	 */
	@Override
	public void onSalonAttentionClick(View v, GroupInfoEntity mSalonName,
			int positon) {
		cacheGroupInfoEntity = SalonHttpUtil.requestAttOrUnfollowToSalon(this,mSalonName);
	}

}
